import {useEffect, useState} from 'react';
import {createId} from '../lib/createId';
import {useUpdate} from './useUpdate';

export type Category = '-' | '+'
export type Tag = {
  id: number;
  name: string;
  category: Category;
}
export const CategoryMap = {'-': '支出', '+': '收入'};

const defaultTags = [['饮食', '-'], ['购物', '-'], ['出行', '-'], ['娱乐', '-'], ['住房', '-'],
  ['宠物', '-'], ['教育', '-'], ['医药', '-'], ['人情支出', '-'], ['工资', '+'], ['二手闲置', '+'], ['人情收入', '+'],
  ['其它支出', '-'], ['其它收入', '+']];

export const getIconName = (tagName: string) => {
  if (tagName === '设置标签')
    return 'setting';
  for (let i = 0; i < defaultTags.length; i++) {
    if (tagName === defaultTags[i][0]) {
      return tagName;
    }
  }
  return '其它';
};

function useTags() {
  const [tags, setTags] = useState<Tag[]>(JSON.parse(window.localStorage.getItem('tags') || '[]'));
  useEffect(() => {
    let localTags = JSON.parse(window.localStorage.getItem('tags') || '[]')
    if (localTags.length === 0) {
      localTags = defaultTags.map(tag => ({id: createId(), name: tag[0], category: tag[1] as Category}));
      window.localStorage.setItem('tags', JSON.stringify(localTags));
    }
    setTags(localTags);

  }, []);

  useUpdate(() => {
    window.localStorage.setItem('tags', JSON.stringify(tags));
  }, [tags]);

  const doesTagNameExist = (tagName: string) => !!tags.filter(tag => tag.name === tagName).length

  const findTag = (tagId: number) => (tags.filter((tag) => tag.id === tagId)[0]);

  const addTag = (obj: { name: string; category: Category }) => {
    const id = createId();
    setTags((prevTags) => [...prevTags, {id, ...obj}]);
    return id;
  };

  const updateTag = (id: number, obj: { name: string, category: Category },) => {
    setTags((prevTags) => prevTags.map(tag => tag.id === id ? {id, ...obj} : tag));
  };

  const deleteTag = (id: number) => {
    setTags((prevTags) => prevTags.filter(tag => tag.id !== id));
  };

  return {tags, doesTagNameExist, findTag, getIconName, addTag, updateTag, deleteTag};
}

export {useTags};